package com.tianji.jersey.resource.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.representation.Form;

public class HttpResourceClientImpl<T> implements HttpResourceClient<T> {
	private WebResource resource;
	private Builder builder;
	private String acceptType = "application/xml";
	private String contentType = "application/xml";
	private Class<T> clazz;

	public HttpResourceClientImpl(String url) {
		Client client = Client.create();
		resource = client.resource(url);
		
	}
	public HttpResourceClientImpl(Class<T> clazz,String url) {
		this.clazz = clazz;
		Client client = Client.create();
		resource = client.resource(url);
		
	}
	private void initType(){
		this.builder = resource.accept(acceptType).type(contentType);
	}
	@Override
	public HttpResourceClient<T> setAcceptType(String acceptType) {
		this.acceptType = acceptType;
		return this;
	}
	@Override
	public HttpResourceClient<T> setContentType(String contentType) {
		this.contentType = contentType;
		return this;
	}
	@Override
	public T get() {
		initType();
		return builder.get(clazz);
	}

	@Override
	public void post() {
		initType();
		resource.post();
	}
	@Override
	public void postNoReturn(Object obj) {
		resource.post(obj);
	}
	@Override
	public T post(Form form) {
		initType();
		if (form != null) {
			return builder.post(clazz, form);
		} else {
			return builder.post(clazz, new Form());
		}
	}
	@Override
	public T post(Object obj) {
		initType();
		return builder.post(clazz,obj);
	}

	@Override
	public T put(Form form) {
		initType();
		if (form != null) {
			return builder.put(clazz, form);
		} else {
			return builder.put(clazz, new Form());
		}
	}

	@Override
	public void putNoReturn(Object obj) {
		resource.put(obj);
	}
	
	@Override
	public T put(Object obj) {
		initType();
		return builder.put(clazz,obj);
	}
	@Override
	public void deleteNoReturn(Object obj) {
		initType();
		builder.delete(obj);
		//resource.delete(obj);
	}
	@Override
	public void delete() {
		initType();
		resource.delete();
	}

	@Override
	public T delete(Form form) {
		initType();
		if (form != null) {
			return builder.delete(clazz, form);
		} else {
			return builder.delete(clazz, new Form());
		}
	}
	
	@Override
	public T delete(Object obj) {
		initType();
		return builder.delete(clazz,obj);
	}
	

}
